package com.tianji.remark.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.entity.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;
import static com.tianji.remark.constants.RedisConstants.LIKES_BIZ_KEY_PREFIX;
import static com.tianji.remark.constants.RedisConstants.LIKE_TIMES_KEY_PREFIX;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-23
 */
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final RabbitMqHelper mqHelper;
    private final StringRedisTemplate redisTemplate;

    /**
     * 1、点赞或者取消点赞（Day6 - 课堂）
     *
     * @param recordFormDTO
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO recordFormDTO) {
        //1、基于前端参数，判断是执行点赞还是取消点赞
        boolean success = recordFormDTO.getLiked() ? like(recordFormDTO) : unLike(recordFormDTO);

        //2、判断是否执行成功，如果失败，直接结束
        if (!success) {
            return;
        }

        //3、如果执行成功，统计点赞数
        Long likeTimes = redisTemplate.opsForSet().size(LIKES_BIZ_KEY_PREFIX + recordFormDTO.getBizId());
        if (ObjectUtils.isEmpty(likeTimes)) {
            return;
        }

        //4、缓存总数到redis
        redisTemplate.opsForZSet().add(LIKE_TIMES_KEY_PREFIX + recordFormDTO.getBizType(),
                recordFormDTO.getBizId().toString(), likeTimes);
    }

    /**
     * 2、查询点赞记录
     *
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {  // [1 , 2 ,3 ,4 ]
        //1、获取登录用户ID
        Long userId = UserContext.getUser();

        //2、查询点赞记录  [true,false,true,true]
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                src.sIsMember(LIKES_BIZ_KEY_PREFIX + bizId,userId.toString());
            }
            return null;
        });

        //3、返回结果
        /*Set<Long> bizIdSet = new HashSet<>();
        for (int i = 0; i < objects.size(); i++) {
            Boolean o = (Boolean) objects.get(i);
            if(o){
                Long bizId = bizIds.get(i);
                bizIdSet.add(bizId);
            }
        }*/
        return IntStream.range(0,objects.size())
                .filter(i -> (Boolean) objects.get(i))
                .mapToObj(i -> bizIds.get(i))
                .collect(Collectors.toSet());
    }

    /**
     * 3、定时读取zset中的点赞数信息并且发送消息至业务方
     *
     * @param bizType
     * @param maxBizSize
     */
    @Override
    public void readLikeTimesAndSendMessage(String bizType, int maxBizSize) {
        //1、读取并移除redis zset中缓存的点赞总数 (元组)
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(LIKE_TIMES_KEY_PREFIX + bizType, maxBizSize);
        while(ObjectUtil.isNotEmpty(typedTuples)){
            //2、数据转换
            List<LikedTimesDTO> list = new ArrayList<>(typedTuples.size());
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String bizId = typedTuple.getValue();//bizId
                Double likeTimes = typedTuple.getScore();
                list.add(LikedTimesDTO.of(Long.valueOf(bizId),likeTimes.intValue()));
            }
            //3、发送MQ消息
            mqHelper.send(
                    LIKE_RECORD_EXCHANGE,
                    StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, bizType),
                    list);
            //4、继续查询一轮（30条数据）
            typedTuples = redisTemplate.opsForZSet().popMin(LIKE_TIMES_KEY_PREFIX + bizType, maxBizSize);
        }
    }

    private boolean unLike(LikeRecordFormDTO recordFormDTO) {
        //1、组装大key
        String key = LIKES_BIZ_KEY_PREFIX + recordFormDTO.getBizId();

        //2、执行SREM命令，将点赞人从指定点赞集合中删除
        Long result = redisTemplate.opsForSet().remove(key, UserContext.getUser().toString());
        return result != null && result > 0;
    }

    private boolean like(LikeRecordFormDTO recordFormDTO) {
        //1、组装大key
        String key = LIKES_BIZ_KEY_PREFIX + recordFormDTO.getBizId();

        //2、执行SADD命令，添加点赞人到点赞集合中
        Long result = redisTemplate.opsForSet().add(key, UserContext.getUser().toString());
        return result != null && result > 0;
    }
}
